package com.tuniu.agents.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Utility class for generating and managing incrementing numbers using Redis.
 */
public class NumberingUtil {

    /**
     * Prefix for Redis keys used by this utility.
     */
    public static final String KEY_NUMBER = "number_key";

    private static StringRedisTemplate redisTemplate;

    /**
     * Injects the StringRedisTemplate instance via Spring.
     * @param template the StringRedisTemplate to use
     */
    public static void setRedisTemplate(StringRedisTemplate template) {
        redisTemplate = template;
    }

    /**
     * Increments the value of the specified key by 1 and sets an expiration time.
     * @param key the Redis key
     * @param expireSeconds expiration time in seconds
     * @return the incremented value
     */
    public static Long incrWithExpire(String key, long expireSeconds) {
        Long value = redisTemplate.opsForValue().increment(KEY_NUMBER + key, 1);
        redisTemplate.expire(key, expireSeconds, TimeUnit.SECONDS);
        return value;
    }

    /**
     * Increments the value of the specified key by 1 and sets a default expiration time (120 seconds).
     * @param key the Redis key
     * @return the incremented value
     */
    public static Long incrWithExpire(String key) {
        return incrWithExpire(key, 120);
    }

    public static String getNumberMarkdown(String markdown, String text, Long index) {
        return StringUtils.replaceOnce(markdown, text, text + "[[%d]](event://action=send&content=%d) ".formatted(index, index));
    }

    /**
     * Resets the value of the specified key to zero.
     * @param key the Redis key
     */
    public static void reset(String key) {
        redisTemplate.opsForValue().set(KEY_NUMBER + key, "0");
    }

}
